import React, { Component } from 'react';
import {messages} from "share/common";
import { Checkbox, Button, message, Modal, Row, Select} from "antd";
import financeViewService from "./corporate-payment-report-view.service";
import errorMessage from 'share/errorMessage';
import borrowService from "../../loan-billing/borrow-and-return.service";
const CheckboxGroup = Checkbox.Group;

class GenerateBatch extends Component {

  state = {
    batchBtnLoading: false,
    batchSize: 100,
    checkedPrintType: localStorage.getItem('hly.print-type') ? JSON.parse(localStorage.getItem('hly.print-type')) : ['BILLS']
  };

  printTypeOptions = [{
    label: messages('expense-1.key643')/*单据*/,
    value: 'BILLS'
  }, {
    label: messages('finance-9.key106')/*发票原件（PDF或OFD）*/,
    value: 'RECEIPT_PDF'
  }, {
    label: messages('expense-1.key645')/*发票图片*/,
    value: 'RECEIPT_IMAGE'
  }];

  onChangePrintType = checkedPrintType => this.setState({ checkedPrintType }, () => localStorage.setItem('hly.print-type', JSON.stringify(checkedPrintType)));

  choosePrintType = e => {
    const { mode, needPreventDefault } = this.props;
    const { checkedPrintType } = this.state;
    let self = this;
    if(needPreventDefault) {
      e.preventDefault();
      e.stopPropagation();
      e.cancelBubble = true;
    }
    Modal.confirm({
      title: messages('expense-1.key646')/*设定对象*/,
      width: 460,
      content: (
        <div>
          <p>{messages('expense-1.key647')/*请设定 打印/生成 批次的对象*/}</p>
          <CheckboxGroup
            options={this.printTypeOptions}
            defaultValue={localStorage.getItem('hly.print-type') ? JSON.parse(localStorage.getItem('hly.print-type')) : ['BILLS']}
            onChange={this.onChangePrintType}
          />
          <p className='font-description'>
           {messages('finance-9.key107')/*发票原件与发票图片同时勾选时，同一张发票优先取用发票原件*/}
          </p>
        </div>
      ),
      onOk: () => {
        if(!self.state.checkedPrintType.length) {
          message.warn(messages('expense-1.key649')/*设定对象不可为空*/);
          return;
        }
        if(mode === 'single')
          this.print();
        else
          this.toGenerateExpenseBatch()
      }
    })
  };

  //单个单据生成批次的 直接下载打印
  print = () => {
    const { checkedPrintType } = this.state;
    const { isExpenseReportView, params } = this.props;
    if (!params.entityOID) {
      return;
    }
    if (params.entityType === 1002) {
      let settingObjects = checkedPrintType.join('&settingObjects=');
      financeViewService.printExpenseReport(params.entityOID, settingObjects, isExpenseReportView)
      .then(res => {
        window.open(res.data.fileURL, '_blank');
      }).catch(e => {
        errorMessage(e.response);
      });
    } else {
      borrowService.printLoanApplication(params.entityOID)
        .then(res => {
          window.open(res.data.link, '_blank');
        });
    }
  };

  //报销单 - 生成批次
  toGenerateExpenseBatch = () => {
    this.setState({ batchBtnLoading: true });
    const { params, onOk } = this.props;
    const { checkedPrintType } = this.state;
    const { batchSize } = this.state;
    financeViewService.createBatch({ ...params, batchSize, settingObjects: checkedPrintType }).then(res => {
      this.setState({ batchBtnLoading: false });
      if (res.data.total) {
        message.success(messages('expense-1.key650')/*批次生成成功*/);
        onOk && onOk();
      } else {
        message.error(messages('expense-1.key651')/*批次号为空的单据才可生成批次！*/)
      }
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ batchBtnLoading: false })
    })
  };

  render() {
    const { batchBtnLoading } = this.state;
    const { name, onClick, href, ...restProps } = this.props.btnProps;
    return (
      React.createElement(
        href !== undefined ? 'a' : Button,
        {loading: batchBtnLoading, onClick: this.choosePrintType, ...restProps},
        name || messages('expense-1.key641')/*生成批次*/
      )
    );
  }
}

export default GenerateBatch;
